<template>
  <div class="container">
    <el-card>
      <el-steps :active="step" align-center class="time-step">
        <el-step title="Step 1" description="种类选择" @click="step > 1 && (step = 1)" />
        <el-step title="Step 2" description="内容编辑" @click="step > 2 && (step = 2)" />
        <el-step title="Step 3" description="文章预览" @click="step > 3 && (step = 3)" />
        <el-step title="Step 4" description="文章提交" />
      </el-steps>

      <!-- 第一步 -->
      <el-form label-width="120px" v-if="step == 1" ref="articleFormRef" :model="articleInfo" :rules="articleRules">
        <el-form-item label="文章标题：" prop="title">
          <el-input v-model.trim="articleInfo.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类：" prop="category">
          <el-select v-model="articleInfo.category" class="m-2" placeholder="文章分类" allow-create filterable>
            <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章标签：" prop="tags">
          <!-- <el-tag v-for="tag in articleInfo.tags" :key="tag" class="mx-1" closable :disable-transitions="false"
            @close="handleClose(tag)"> 
            {{ tag }}
          </el-tag> -->
          <el-select v-model="articleInfo.tags" multiple filterable allow-create default-first-option
            :reserve-keyword="false" placeholder="选择标签">
            <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <!-- <el-input v-if="inputTag.inputVisible" ref="InputRef" v-model="inputTag.inputVal" class="ml-1 w-20" size="small"
            @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
          <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
            + New Tag
          </el-button> -->
        </el-form-item>
        <el-form-item label="文章简介：" prop="introduction">
          <el-input v-model.trim="articleInfo.introduction" type="textarea" rows="6" placeholder="请输入文章简介"></el-input>
        </el-form-item>
        <el-form-item label="权限：" prop="right">
          <el-radio-group v-model="articleInfo.right">
            <el-radio-button label="私有"></el-radio-button>
            <el-radio-button label="公开"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <div class="next-step">
          <el-button type="primary" @click="nextStep(articleFormRef)">下一步</el-button>
        </div>
      </el-form>
      <!-- 第二部内容编辑 -->
      <TextEdit v-if="step === 2" :textEdit="textEdit" :content="articleInfo.content" @value-change="contentChange">
      </TextEdit>
      <!-- 第四步 文章提交 -->
      <el-form label-width="120px" v-if="step === 4">
        <el-form-item label="作者：">
          <el-input :value="userInfoStore.userInfo.nickname" disabled></el-input>
        </el-form-item>
        <el-form-item label="文章标题：">
          <el-input :value="articleInfo.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="文章分类：">
          <el-input :value="articleInfo.category" disabled></el-input>
        </el-form-item>
        <el-form-item label="文章权限：">
          <el-input :value="articleInfo.right" disabled></el-input>
        </el-form-item>
        <el-form-item label="文章标签：">
          <el-tag class="mx-1" v-for="tag in articleInfo.tags" type="info">{{ tag }}</el-tag>
        </el-form-item>
        <el-form-item label="文章简介：">
          <el-input :value="articleInfo.introduction" type="textarea" disabled :rows="4" placeholder="请输入文章简介"></el-input>
        </el-form-item>
        <el-form-item label="文章内容：">
          <p v-html="articleInfo.content" disabled class="passage-content"> </p>
        </el-form-item>
      </el-form>
    </el-card>
    <!--第三步 文章预览  -->
    <el-card class="passage-review" v-if="step === 3">
      <template #header>
        <h1 style="text-align: center;font-size: 18px; "> {{ articleInfo.title }} </h1>
      </template>
      <p v-html="articleInfo.content"></p>
    </el-card>

    <el-card class="next-step" v-show="step > 1">
      <el-button type="info" @click="step--">上一步</el-button>
      <el-button type="primary" @click="nextStep" v-show="step < 4">下一步</el-button>
      <el-button type="primary" @click="submitPassage" v-show="step === 4">提交</el-button>
    </el-card>
  </div>
</template> 
<script setup lang='ts' name="common_step">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useUserInfoStore } from '@/stores';
import { type FormRules, type FormInstance, ElInput, ElMessage, ElNotification } from 'element-plus'
import TextEdit from '@/components/textEdit/textEdit.vue'
import { delHtmlTag } from '@/utils';
import { addArticle, findOneArticle, updateArticle } from '@/api'
const userInfoStore = useUserInfoStore()
const { uuid } = userInfoStore.userInfo
const router = useRouter()
const route = useRoute()
const props = defineProps<{
  type?: string,
}>()
interface articleObj {
  title: string,
  category: string,
  tags: Array<string>,
  introduction: string,
  right: '公开' | '私有',
  content: string,
  publish_status: number
}

onMounted(async () => {
  if (props.type == 'update') {
    const res = await findOneArticle(+route.params.id, uuid)
    const { title, category, introduction, tags, right, content, publish_status } = res.data.data
    const categories = category.split(',')

    const statusObj = { '待审核': 0, '待发布': 1, '已发布': 2, '未通过': 3, '草稿箱': 4, '已删除': 5 }
    const tag = tags.map((item: { name: string }) => {
      return item.name
    });
    articleInfo.value = {
      title,
      category: categories,
      introduction,
      tags: tag,
      right,
      content,
      publish_status: statusObj[publish_status as '待审核']
    }
  }
})

const inputTag = reactive({
  inputVal: '',
  inputVisible: false
})
const InputRef = ref<InstanceType<typeof ElInput>>()
const step = ref<number>(1)
const categories = ref([{
  value: 'HTML',
  label: 'HTML',
},
{
  value: 'CSS',
  label: 'CSS',
},
{
  value: 'JavaScript',
  label: 'JavaScript',
},])
const articleInfo = ref<articleObj>({
  title: '',
  category: '',
  introduction: '',
  tags: [],
  right: '私有',
  content: '',
  publish_status: 0
})
const articleFormRef = ref<FormInstance>()
const articleRules = reactive<FormRules>({
  title: [
    { required: true, message: '标题为必填项', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择类别', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请填写标签', trigger: 'blur' },
    {
      validator(rule, value, callback) {
        if (articleInfo.value.tags.length <= 0) {
          callback(new Error('至少填写一个标签'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  introduction: [
    { required: true, message: '请输入文章简介', trigger: 'blur' }
  ],
  right: [
    { required: true, message: '请输入权限', trigger: 'blur' }
  ]
})
//富文本编辑器数据
const textEdit = reactive({
  mode: 'default',
  editorConfig: { placeholder: '请输入内容...' },
})
//tags方法
const handleClose = (tag: string) => {
  articleInfo.value.tags.splice(articleInfo.value.tags.indexOf(tag), 1)
}
const showInput = () => {
  inputTag.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
const handleInputConfirm = () => {
  if (inputTag.inputVal) {
    articleInfo.value.tags.push(inputTag.inputVal)
  }
  inputTag.inputVisible = false
  inputTag.inputVal = ''
}
//富文本编辑器获取内容 
const contentChange = (valueHtml: string) => {
  articleInfo.value.content = valueHtml

}
//下一步
const nextStep = (formEl: FormInstance | undefined) => {
  if (step.value == 1) {
    if (!formEl) return
    formEl.validate(async (valid, error) => {
      if (valid) {
        //校验通过
        return step.value++
      }
    })
  }
  if (step.value == 2) {
    if (delHtmlTag(articleInfo.value.content)?.trim() === '') {
      return ElMessage({
        type: 'error',
        message: '内容不能为空!'
      })
    } else {
      return step.value++
    }
  }
  step.value == 3 && step.value++
}

//提交文章
const submitPassage = async () => {
  //区分是更新还是添加
  // updateArticle()
  const { title, category, introduction, tags, right, content } = articleInfo.value
  //整理数据
  const data = {
    uuid: userInfoStore.userInfo.uuid,
    title,
    content: content,
    tags,
    category,
    author: userInfoStore.userInfo.nickname,
    publish_status: right === '公开' ? 0 : 4,
    introduction,
    right
  }
  try {
    //更新文章
    if (props.type === 'update') {
      const res = await updateArticle(+route.params.id, data)
      ElNotification({
        title: 'Success',
        message: res.data.msg,
        type: 'success',
      })
      router.push({ name: 'update_article' })
    } else {
      //添加文章
      const res = await addArticle(data)
      ElNotification({
        title: 'Success',
        message: res.data.msg,
        type: 'success',
      })
      router.push({ name: 'awaitpass_article' })
    }
  } catch (error) {
    ElNotification({
      title: 'error',
      message: '错误',
      type: 'error',
    })
  }
}
</script>
<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  margin: 0 20px;

  .passage-review {
    margin: 10px 0;
    min-height: 400px;
  }
}

.choose-container,
.time-step {
  margin: 0 20px 20px;
}

.mx-1 {
  margin: 0 5px;
}

.next-step {
  text-align: center;
  margin: 10px 0;
}

.passage-content {
  width: 100%;
  border: 1px solid #c0c4cc;
  background-color: rgb(154, 240, 240, .3);
}
</style>